// useUpdateCheck.js
import { ref, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import { ElMessageBox } from 'element-plus'

export function useUpdateCheck() {
  let intervalId: any = null

  const showUpdateConfirmation = () => {
    return ElMessageBox.confirm(
      '新版本已发布，请立即刷新以获取最新内容',
      '提示',
      {
        confirmButtonText: '刷新',
        showClose: false,
        showCancelButton: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: 'warning'
      }
    )
  }
  const checkUpdate = (reload = false) => {
    const url = `/version.json?timestamp=${Date.now()}`;
    axios.get(url).then(response => {
        const latestVersion = response.data.version;
        const localVersion = localStorage.getItem("msc_admin_version");
        if (!localVersion) {
          localStorage.setItem("msc_admin_version", latestVersion);
          return;
        }
        if (latestVersion !== localVersion && latestVersion !== undefined) {
          localStorage.setItem("msc_admin_version", latestVersion);
          if (reload) {
            location.reload();
          } else {
            showUpdateConfirmation().then(() => {
              location.reload();
            })
            .catch(error => {
              console.error("用户取消了更新", error);
            });
          }
        }
      })
      .catch(err => {
        console.error("检查更新失败:", err);
      });
  };

  onMounted(() => {
    intervalId = setInterval(checkUpdate, 300_000)
  })

  onUnmounted(() => {
    if (intervalId) {
      clearInterval(intervalId)
    }
  })

  return {
    checkUpdate
  }
}